package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.PublicKey;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    public Result queryByIdWithPassThrough(Long id) {
        Shop shop = cacheClient.getWithPassThrough(
                RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
                id2 -> getById(id2),
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 缓存穿透问题  redis中写空值
     * 缓存击穿问题  使用互斥锁 + 缓存穿透
     *
     * @param id
     * @return
     */
    public Result queryByIdMutex(Long id) {

        String key = RedisConstants.CACHE_SHOP_KEY + id;

        // 1.从redis中查询店铺信息
        String shopJsonString = stringRedisTemplate.opsForValue().get(key);
        // 2. 查到直接返回
        if (StrUtil.isNotBlank(shopJsonString)) {
            return Result.ok(JSONUtil.toBean(shopJsonString, Shop.class));
        }
        if (shopJsonString != null) {
            // 缓存穿透问题 返回错误信息
            return Result.fail("店铺不存在");
        }
        // 3. 没有查到，从数据库中查询
        // 解决缓存击穿问题 需要先获取互斥锁(简易版)
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isGetLock = tryLock(lockKey);
            if (!isGetLock) {
                // 获取失败 缓存并重试
                Thread.sleep(50);
                return queryById(id);
            }
            // 再查一遍
            shopJsonString = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(shopJsonString)) {
                return Result.ok(JSONUtil.toBean(shopJsonString, Shop.class));
            }

            shop = getById(id);
            // 睡眠一下 模拟重建缓存的长时间
            Thread.sleep(200);
            if (shop == null) {
                // 可能会引起缓存穿透问题
                // 采用缓存空值的方法解决
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return Result.fail("店铺不存在");
            }
            // 4. 写入redis 并设置时间
            stringRedisTemplate.opsForValue().set(
                    key,
                    JSONUtil.toJsonStr(shop),
                    RedisConstants.CACHE_SHOP_TTL,
                    TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            unLock(lockKey);
        }
        // 5. 返回
        return Result.ok(shop);
    }


    //简单的线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    /**
     * 缓存击穿问题 使用逻辑过期 + 互斥锁
     *
     * @param id
     * @return
     */
    public Result queryByIdLogicalExpire(Long id) {

        String key = RedisConstants.CACHE_SHOP_KEY + id;

        // 1.从redis中查询店铺信息
        String shopJsonString = stringRedisTemplate.opsForValue().get(key);
        // 2. 没查到直接返回
        if (StrUtil.isBlank(shopJsonString)) {
            return Result.fail("非热点数据");
        }
        // 查到了 判断是否过期
        RedisData redisData = JSONUtil.toBean(shopJsonString, RedisData.class);
        // redisDate 中的data是Object类型 所以再上面JsonUtil转换时 无法将data直接转换Shop对象
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
            // 未过期 直接返回
            return Result.ok(shop);
        }
        // 过期了 需要重建缓存 新建一个线程进行缓存重建
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isGetLock = tryLock(lockKey);
        if (isGetLock) {
            // 获取锁成功 先判断是不是其他线程刚重建好缓存释放的锁
            shopJsonString = stringRedisTemplate.opsForValue().get(key);
            // 查到了 判断是否过期
            redisData = JSONUtil.toBean(shopJsonString, RedisData.class);
            shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
            if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
                // 未过期 直接返回
                return Result.ok(shop);
            }
            // 缓存过期了 新建一个线程进行缓存重建(使用线程池的方式)
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    saveShop2Redis(id, RedisConstants.CACHE_SHOP_TTL);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    // 重建后需要释放锁
                    unLock(lockKey);
                }
            });
        }
        // 无论是重建完成 还是获取锁失败 都会返回信息
        return Result.ok(shop);
    }

    public Result queryByIdLogicalExpire2(Long id) {
        Shop shop = cacheClient.getWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
                id2 -> getById(id2),
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if(shop == null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    @Override
    public Result queryById(Long id) {

//        return queryByIdWithPassThrough(id);
        return queryByIdLogicalExpire2(id);
    }


    @Override
    @Transactional
    public Result saveShop(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        save(shop);
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok(shop.getId());
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        updateById(shop);
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if(x == null || y == null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 在redis中查询 需要计算分页参数
        int size = SystemConstants.DEFAULT_PAGE_SIZE;
        int from = (current - 1) * size;
        int end = current * size;
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        // GeoResults 继承自Iterable集合
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        // redis中查不出来 则返回空
        if(geoResults == null){
            return Result.ok(Collections.emptyList());
        }
        //
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = geoResults.getContent();
        if(list.size() <  from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 获取shopId
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 获取距离
            Distance distance = result.getDistance();
            System.out.println("距离为：" + distance.getValue());
            distanceMap.put(shopIdStr, distance);
        });
        // 根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids)
                .last("ORDER BY FIELD( id," + idStr + ")")
                .list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }


    private boolean tryLock(String key) {
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(lock);
    }

    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        Shop shop = getById(id);
        Thread.sleep(200);
        if (shop != null) {
            RedisData redisData = new RedisData();
            redisData.setData(shop);
            redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
        }

    }
}
